<?php

namespace App\Http\Controllers;

use App\Models\Project;
use App\Models\ProjectHire;
use App\Models\Team;
use App\Models\WechatTempMsg;
use Carbon\Carbon;
use function GuzzleHttp\Psr7\str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ProjectController extends Controller
{
    public function show(Request $request, $id) {
        $node = Project::findOrFail($id);
        $node->load('org');
        $node->load('team');
        $data = $node->toArray();

        $data['canEdit'] = 0;

        $user = $request->user();
        if (
            $user->type == 4 ||
            $user->type == 5 ||
            $user->type == 3 ||
            $user->type == 2 && ($user->team->auth_exempt_project || $node->verify_status == -1) && $user->team_id == $node->team_id
        ) {
            $data['canEdit'] = 1;
        }

        return $this->returnJSON($data, 0, 'ok');
    }

    public function index(Request $request) {
        $perPage = $request->get('perPage', 10);
        $query = Project::with('team');

        $query->where('verify_status', '=', 1);

        $user = $request->user();

        if ($user->type == 3) {
            $query->where('org_id', '=', $user->org_id);
        } else if ($user->type == 2) {
            $query->where('org_id', '=', $user->team->org_id);
            $teamIds = [];
            $teamIds[] = $user->team_id;
            foreach (Team::whereDescendantOf($user->team)->select('id')->where('org_id',$user->team->org_id)->get()->toArray() as $item) {
                $teamIds[] = $item['id'];
            }
            $query->whereIn('team_id', $teamIds);
        } else if ($user->type == 4 && $request->has('org_id')) {
            $query->where('org_id', '=', $request->get('org_id'));
        } else if ($user->type == 5 && $request->has('org_id')) {
            $query->where('org_id', '=', $request->get('org_id'));
        }

        if ($user->type == 5) {
            $org_list = $user->platform->org_list;
            $query = $query->whereIn('org_id', $org_list);
//            $info['data'] = $query->get()->toArray();
//            $info['total'] = count($org_list);
        }

        if ($request->has('team_id') && intval($request->get('team_id'))) {
            $query->where('team_id', '=', $request->get('team_id'));

        }

        if ($request->has('team_type')) {
            $teamIds = [];
            $teams = Team::select('id')->whereRaw('FIND_IN_SET( \''.$request->get('team_type') .'\', type)')->get();
            foreach ($teams as $team) {
                $teamIds[] = $team->id;
            }
            $query->whereIn('team_id', $teamIds);
        }

        if ($request->has('project_type')) {
            $query->whereRaw('FIND_IN_SET( \''.$request->get('project_type') .'\', project_type)');
        }

        if ($request->has('name')) {
            $query->where('name', 'like', '%' .$request->get('name'). '%');
        }

        // 2 招募中
        // 3 已招满
        // 4 进行中
        // 5 已结束
        if ($request->get('progress') == 2) {
            $query->where('join_end', '>=', date('Y-m-d H:i:s'));
            $query->whereRaw('join_people_count < people_count');
            $query->where('status', '=', '1');
//            dd($query->toSql());
        } else if ($request->get('progress') == 3) {
//            $query->where('begin', '>', date('Y-m-d H:i:s'));
            $query->whereRaw('join_people_count >= people_count');
            $query->where('status', '=', '1');
        } else if ($request->get('progress') == 4) {
            $query->where('begin', '<=', date('Y-m-d H:i:s'));
            $query->where('end', '>=', date('Y-m-d H:i:s'));
            $query->where('status', '=', '1');
        } else if ($request->get('progress') == 5) {
            $query->where('end', '<', date('Y-m-d H:i:s'));
        }



        //列表按id倒排
        $query->orderBy('recommend_time', 'desc');
        $query->orderBy('publish_time', 'desc');
        $query->orderBy('id', 'desc');

        $info = $query->paginate($perPage)->toArray();

        $ids = array_map(function($item) {
            return $item['id'];
        }, $info['data']);


        $applies = DB::table('user_project')
            ->select(DB::raw('count(*) as apply_count, project_id'))
            ->whereIn('project_id', $ids)
            ->groupBy('project_id')
            ->get();

        $applyMap = [];
        foreach ($applies as $apply) {
            $applyMap[$apply->project_id] = $apply;
        }

        foreach ($info['data'] as &$item) {
            if (isset($applyMap[$item['id']])) {
                $item['apply_count'] = $applyMap[$item['id']]->apply_count;
            } else {
                $item['apply_count'] = 0;
            }
            if ($request->get('progress') == 2) {
                $item['progress'] = 2;
            } else if ($request->get('progress') == 3) {
                $item['progress'] = 3;
            } else if ($request->get('progress') == 4) {
                $item['progress'] = 4;
            } else if ($request->get('progress') == 5) {
                $item['progress'] = 5;
            }
        }
//        Log::info($info);

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function store(Request $request) {
        if ($request->has('id')) {
            return $this->update($request, $request->get('id'));
        }

        $user = $request->user();

        $this->validate($request, [
            'org_id' => $user->type == 4 || $user->type == 5 ? 'required' : '',
            'team_id' => $user->type == 3 || $user->type == 4 || $user->type == 5 ? 'required' : '',
            'name' => 'required|max:32',
            'service_target' => 'required|max:255',
            'project_type' => 'required|max:255',
            'volunteer_security' => 'max:255',
            'list_photo' => 'max:255',
            'region' => 'required',
            'address' => 'required',
            'begin' => 'required',
            'end' => 'required|not_before:begin',
            'join_end' => 'required',
            'content' => 'required',
            'contact_name' => 'required|max:32',
            'contact_phone' => 'required|max:32',
            'contact_phone_public' => 'required',
            'work_tel' => 'max:32',
            'work_email' => $request->has('work_email') ? 'max:255|email' : '',
            'people_count' => 'required',
            'reward_time' => 'required',
        ]);

        $node = new Project();
        $data = $request->only([
            'org_id',
            'team_id',
            'list_photo',
            'name',
            'service_target',
            'region',
            'address',
            'begin',
            'end',
            'join_end',
            'project_type',
            'volunteer_security',
            'content',
            'photo',
            'contact_name',
            'contact_phone',
            'contact_phone_public',
            'work_tel',
            'work_tel_public',
            'work_email',
            'people_count',
            'reward_time',
            'custom_payment_config',
            'custom_config',
        ]);

//        dd(gettype($data['custom_config']), gettype($data['custom_config'][0]),$data['custom_config'][0]);
//        dd(uniqid('p'));
//        dd($data['custom_config'], genKey($data['custom_config']), $data['custom_config']);

        // default values;
        $data['identifier'] = '';
        $data['verify_msg'] = '';
        $data['verify_status'] = 0;
        $data['join_people_count'] = 0;
        $data['browse_times'] = 0;
        $data['list_photo'] = isset($data['list_photo']) ? $data['list_photo'] : '';
        $data['photo'] = isset($data['photo']) ? $data['photo'] : '';
        $data['work_tel'] = isset($data['work_tel']) ? $data['work_tel'] : '';
        $data['work_tel_public'] = isset($data['work_tel_public']) ? $data['work_tel_public'] : 0;
        $data['work_email'] = isset($data['work_email']) ? $data['work_email'] : '';
        $data['volunteer_security'] = isset($data['volunteer_security']) ? $data['volunteer_security'] : '';
        $data['custom_config'] = genKey($data['custom_config']);
        $data['custom_payment_config'] = genKey($data['custom_payment_config']);

        if ($request->get('op') == 'save') {
            $data['verify_status'] = -1;
        } else if ($user->type == 4 || $user->type == 5 || $user->type == 3 || $user->type == 2 && $user->team->auth_exempt_project) {
            $data['verify_status'] = 1;
        }

        if ($user->type == 3) {
            $data['org_id'] = $user->org_id;
        } else if ($user->type == 2) {
            $data['org_id'] = $user->team->org_id;
            $data['team_id'] = $user->team_id;
        }
//        dd($data);
        $node->fill($data);

        if ($node->save()) {

            $node->syncServiceType();
            $node->syncServiceTarget();
            $node->fill([
                'identifier' => 'ZDX'.date('Ymd').sprintf("%08d",$node->id)
            ]);
            $node->save();
            $node->load('org');
            $node->load('team');
            $data = $node->toArray();


            return $this->returnJSON($data, 0, '新增成功');
        }
        return $this->returnJSON(null, 500, '新建失败');
    }

    public function update(Request $request, $id) {
        $node = Project::findOrFail($id);

        $user = $request->user();
        if (!($user->type == 4 || $user->type == 5 || $user->type == 3 || $user->type == 2 && $user->team->auth_exempt_project || $node->verify_status == -1)) {
            throw new \Exception('当前项目已提交不可编辑');
        }

        $this->validate($request, [
            'org_id' => $user->org_id ? '' : 'required',
            'team_id' => 'required',
            'name' => 'required|max:32',
            'service_target' => 'required|max:255',
            'project_type' => 'required|max:255',
            'volunteer_security' => 'max:255',
            'list_photo' => 'max:255',
            'region' => 'required',
            'address' => 'required',
            'begin' => 'required',
            'end' => 'required|not_before:begin',
            'join_end' => 'required',
            'content' => 'required',
            'contact_name' => 'required|max:32',
            'contact_phone' => 'required|max:32',
            'contact_phone_public' => 'required',
            'work_tel' => 'max:32',
            'work_email' => $request->has('work_email') ? 'max:255|email' : '',
            'people_count' => 'required',
            'reward_time' => 'required',
        ]);

        $data = $request->only([
            'org_id',
            'team_id',
            'list_photo',
            'name',
            'service_target',
            'region',
            'address',
            'begin',
            'end',
            'join_end',
            'project_type',
            'volunteer_security',
            'content',
            'photo',
            'contact_name',
            'contact_phone',
            'contact_phone_public',
            'work_tel',
            'work_tel_public',
            'work_email',
            'people_count',
            'reward_time',
            'custom_payment_config',
            'custom_config',
        ]);
//        dd($data['custom_config'], $data['custom_payment_config']);

        $data['list_photo'] = isset($data['list_photo']) ? $data['list_photo'] : '';
        $data['photo'] = isset($data['photo']) ? $data['photo'] : '';
        $data['volunteer_security'] = isset($data['volunteer_security']) ? $data['volunteer_security'] : '';
        $data['work_tel'] = isset($data['work_tel']) ? $data['work_tel'] : '';
        $data['work_email'] = isset($data['work_email']) ? $data['work_email'] : '';
        $data['custom_config'] = genKey($data['custom_config']);
        $data['custom_payment_config'] = genKey($data['custom_payment_config']);

        if ($request->get('op') == 'save' && $node->verify_status == -1) {
            $data['verify_status'] = -1;
        } else if ($user->type == 4 || $user->type == 5 || $user->type == 3 || $user->type == 2 && $user->team->auth_exempt_project) {
            $data['verify_status'] = 1;
        } else {
            $data['verify_status'] = 0;
        }

        $node->fill($data);
        if ($node->save()) {

            $node->syncServiceType();
            $node->syncServiceTarget();

            return $this->returnJSON(null, 0, '保存成功');
        }
        return $this->returnJSON(null, 500, '保存失败');
    }


    public function verify(Request $request) {
        $perPage = $request->get('perPage', 10);
        $query = Project::with('team');

        $user = $request->user();
        Team::scoped(['org_id' => 3])->fixTree();
        if ($user->type == 3) {
            $query->where('org_id', '=', $user->org_id);
        } else if ($user->type == 2) {
            if (!$user->team->auth_exempt_project) {
                throw new \Exception('权限不足');
            }

            $teamIds = [];
           // dd($user->team->getBounds());
//            dd(Team::whereDescendantOf($user->team)->select('id')->toSql());
           // dd(Team::query()->whereBetween('_lft', [1,6], 'and', false)->select('id', '_lft', '_rgt')->get()->toArray());
//            dd(Team::whereDescendantOf($user->team)->select('id')->where('org_id',$user->team->org_id)->get()->toArray());
            foreach (Team::whereDescendantOrSelf($user->team)->select('id')->where('org_id',$user->team->org_id)->get()->toArray() as $item) {
                $teamIds[] = $item['id'];
//                Log::info("test");
//                Log::info($teamIds);
            }
            $query->whereIn('team_id', $teamIds);
        } else if ($user->type == 4 && $request->has('org_id')) {
            $query->where('org_id', '=', $request->get('org_id'));
        }else if ($user->type == 5 && $request->has('org_id')) {
            $query->where('org_id', '=', $request->get('org_id'));
        }

        $query->where('verify_status', '<>', -1);

        if ($request->has('status')) {
            $query->where('verify_status', '=', $request->get('status'));
        }

        $info = $query->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function accept(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $user = $request->user();
        $result = Project::whereIn('id',  $ids)->update(['verify_status' => 1]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            $sms = new \App\Libs\Sms();
            $projectInfo = Project::with(['org','team'])->whereIn('id', $ids)->get()->toArray();
            // 发送短信
            $nodes = [];
            foreach($projectInfo as $item)
            {
                //微信模版消息，项目通过
                WechatTempMsg::add(53, ['project_id'=>$item['id']]);
                $content = '【'.$item['org']['name'].'】您发起的项目《'.$item['name'].'》已通过审核';
                $nodes[]= array('from_user_id'=>$user->id,
                    'title' => $request->get('title', ''),
                    'to_user_id'=>$item['team']['user_id'],
                    'type' => 1,
                    'content' => $content,);
                $ret = $sms->sendTemplateSMS($item['team']['contact_phone'], array($item['name']),209752);
            }
            // 发送站内信
            DB::table('user_message')->insert($nodes);
            return $this->returnJSON($ids, 0, '审核通过');
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }
    public function reject(Request $request, $id)
    {
        $this->validate($request, [
            'reason' => 'required'
        ]);

        $user = $request->user();

        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = Project::whereIn('id',  $ids)->update([
            'verify_status' => 2,
            'verify_msg' => $request->get('reason')
        ]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            $sms = new \App\Libs\Sms();
            $projectInfo = Project::with(['org','team'])->whereIn('id', $ids)->get()->toArray();
            // 发送短信
            $nodes = [];
            foreach($projectInfo as $item)
            {
                //微信模版消息，项目被拒绝
                WechatTempMsg::add(54, ['project_id'=>$item['id']]);
                $content = '【'.$item['org']['name'].'】您发起的项目《'.$item['name'].'》未通过审核，未通过原因 “'.$request->get('reason').'”';
                $nodes[]= array('from_user_id'=>$user->id,
                    'title' => $request->get('title', ''),
                    'to_user_id'=>$item['team']['user_id'],
                    'type' => 1,
                    'content' => $content,);
                $ret = $sms->sendTemplateSMS($item['team']['contact_phone'], array($item['name'], $request->get('reason')),209753);
            }
            // 发送站内信
            DB::table('user_message')->insert($nodes);
            return $this->returnJSON($ids, 0, '驳回成功');
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }

    public function refresh(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        $date = new Carbon();

        $result = Project::whereIn('id',  $ids)->update(['publish_time' => $date->toDateTimeString()]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '刷新成功');
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }

    public function recommend(Request $request, $id)
    {
        $user = $request->user();

        if ($user->tyep == 2) {
            throw new \Exception('权限不足');
        }

        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        $date = new Carbon();

        $result = Project::whereIn('id',  $ids)->update(['recommend_time' => $date->toDateTimeString()]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '置顶成功');
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }

    public function unRecommend(Request $request, $id)
    {
        $user = $request->user();

        if ($user->tyep == 2) {
            throw new \Exception('权限不足');
        }

        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        $date = new Carbon();

        $result = Project::whereIn('id',  $ids)->update(['recommend_time' => null]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '取消置顶成功');
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }

    public function online(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = Project::whereIn('id',  $ids)->update(['status' => 1]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '上架成功');
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }
    public function offline(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = Project::whereIn('id',  $ids)->update(['status' => 0]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '下架成功');
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }
    public function cancel(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = Project::whereIn('id',  $ids)->where('verify_status', '=', '0')->update(['verify_status' => -1]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '撤销提交成功');
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }

    public function draft(Request $request) {
        $perPage = $request->get('perPage', 10);
        $query = Project::query();

        $query->where('verify_status', '=', -1);

        $user = $request->user();

        if ($user->type == 3) {
            $query->where('org_id', '=', $user->org_id);
        } else if ($user->type == 2) {
            $teamIds = [$user->team_id];
//            foreach (Team::whereDescendantOf($user->team)->select('id')->get()->toArray() as $item) {
//                $teamIds[] = $item['id'];
//            }
            $query->whereIn('team_id', $teamIds);
        } else if ($user->type == 4 && $request->has('org_id')) {
            $query->where('org_id', '=', $request->get('org_id'));
        } else if ($user->type == 5 && $request->has('org_id')) {
            $query->where('org_id', '=', $request->get('org_id'));
        }

        $query->orderBy('recommend_time', 'desc');
        $query->orderBy('publish_time', 'desc');
        $query->orderBy('id', 'desc');
        $info = $query->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function pending(Request $request) {
        $perPage = $request->get('perPage', 10);
        $query = Project::query();

        $query->where('verify_status', '=', '0');

        $user = $request->user();

        if ($user->type == 3) {
            $query->where('org_id', '=', $user->org_id);
        } else if ($user->type == 2) {
            $teamIds = [$user->team_id];
//            foreach (Team::whereDescendantOf($user->team)->select('id')->get()->toArray() as $item) {
//                $teamIds[] = $item['id'];
//            }
            $query->whereIn('team_id', $teamIds);
        } else if ($user->type == 4 && $request->has('org_id')) {
            $query->where('org_id', '=', $request->get('org_id'));
        } else if ($user->type == 5 && $request->has('org_id')) {
            $query->where('org_id', '=', $request->get('org_id'));
        }

        $query->orderBy('recommend_time', 'desc');
        $query->orderBy('publish_time', 'desc');
        $query->orderBy('id', 'desc');
        $info = $query->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function processing(Request $request) {
        $perPage = $request->get('perPage', 10);
        $query = Project::query();

        $query->where('verify_status', '=', 1);
        $query->where('status', '=', 1);
        // 从招募时间开始算，因为没有招募开始时间，所以就开始了
        // $query->where('begin', '<', date('Y-m-d H:i:s'));
        $query->where('end', '>', date('Y-m-d H:i:s'));

        $user = $request->user();

        if ($user->type == 3) {
            $query->where('org_id', '=', $user->org_id);
        } else if ($user->type == 2) {
            $teamIds = [$user->team_id];
//            foreach (Team::whereDescendantOf($user->team)->select('id')->get()->toArray() as $item) {
//                $teamIds[] = $item['id'];
//            }
            $query->whereIn('team_id', $teamIds);
        } else if ($user->type == 4 && $request->has('org_id')) {
            $query->where('org_id', '=', $request->get('org_id'));
        } else if ($user->type == 5 && $request->has('org_id')) {
            $query->where('org_id', '=', $request->get('org_id'));
        }

        $query->orderBy('recommend_time', 'desc');
        $query->orderBy('publish_time', 'desc');
        $query->orderBy('id', 'desc');
        $info = $query->paginate($perPage)->toArray();

        $ids = array_map(function($item) {
            return $item['id'];
        }, $info['data']);

        $applies = DB::table('user_project')
            ->select(DB::raw('count(*) as apply_count, project_id'))
            ->whereIn('project_id', $ids)
            ->groupBy('project_id')
            ->get();

        $applyMap = [];
        foreach ($applies as $apply) {
            $applyMap[$apply->project_id] = $apply;
        }

        foreach ($info['data'] as &$item) {
            if (isset($applyMap[$item['id']])) {
                $item['apply_count'] = $applyMap[$item['id']]->apply_count;
            } else {
                $item['apply_count'] = 0;
            }
        }

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function outdated(Request $request) {
        $perPage = $request->get('perPage', 10);
        $query = Project::query();

        $user = $request->user();

        if ($user->type == 3) {
            $query->where('org_id', '=', $user->org_id);
        } else if ($user->type == 2) {
            $teamIds = [$user->team_id];
//            foreach (Team::whereDescendantOf($user->team)->select('id')->get()->toArray() as $item) {
//                $teamIds[] = $item['id'];
//            }
            $query->whereIn('team_id', $teamIds);
        } else if ($user->type == 4 && $request->has('org_id')) {
            $query->where('org_id', '=', $request->get('org_id'));
        } else if ($user->type == 5 && $request->has('org_id')) {
            $query->where('org_id', '=', $request->get('org_id'));
        }

        $query->where(function($query) {
            $query->orWhere('end', '<', date('Y-m-d H:i:s'));
            // $query->orWhere('status', '=', 0);
        });

        $query->orderBy('recommend_time', 'desc');
        $query->orderBy('publish_time', 'desc');
        $query->orderBy('id', 'desc');
        $info = $query->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function buySafe(Request $request, $id) {
        $project = Project::findOrFail($id);

        $team = $project->team;
        $data = [];

//        $data['canBuy'] = 0;
//
//        $date = strtotime(date('Y-m-d', $project->begin).' 00:00:00');
//        if (time() < $date) {
//            $data['canBuy'] = 1;
//        }

        $data['activity_id'] = $project->id;
        $data['token'] = '123456';
        $data['activity_name'] = $project->name;
        $data['activity_code'] = $project->identifier;
        $data['m_name'] = $team->legal_person;
        $data['m_cardno'] = $team->legal_person_id;
        $data['m_mobile'] = $team->contact_phone;
        $data['m_email'] = $team->contact_email;
        $data['m_type'] = '1';


        $query = ProjectHire::with(['user.volunteer'])->where('project_id', '=', $id);
        $query->where('verify_status', '=', 1);
        $hires = $query->get()->toArray();
        $volunteers = [];

        foreach ($hires as $item) {
            if (!isset($item['user']) || !isset($item['user']['volunteer'])) {
                continue;
            }

            $volunteer = $item['user']['volunteer'];


            $volunteers[] = [
                'c_name' => !empty($volunteer['real_name']) ? $volunteer['real_name'] : $item['user']['username'],
                'c_cardno' => $volunteer['id_number'],
                'c_mobile' => $volunteer['phone'],
            ];
        }
        $data['volunteers'] = $volunteers;


        return $this->returnJSON($data, 0, 'ok');
    }
}

/**
 * 预处理，格式化自定义配置信息
 * @param $values
 * @return null
 */
function genKey(&$values) {
    if (gettype($values) !== 'array' || count($values) < 1) return null;
//    dd($values);

    foreach ($values as &$v){
        if($v && array_key_exists('$id', $v)) {
            unset($v['$id']);
        }
        // 不存在key，则添加
        if($v && !array_key_exists('key', $v)) {
            $v['key'] = uniqid('p');
        }

//        dd(1);

        if($v && array_key_exists('options', $v) && $v['options']) {
            $v['options'] = str_replace('，', ',', $v['options']);
//            dd(2);
        }
    }
//    dd($values);
    return $values;
}
